package com.linkhub.oms.admin.modules.supplier.service.impl;
import java.time.LocalDateTime;

import cn.hutool.core.util.IdUtil;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.modules.supplier.domain.param.SupplierAddParam;
import com.linkhub.oms.admin.modules.supplier.domain.vo.SupplierVO;
import com.linkhub.oms.admin.modules.supplier.service.SupplierBizService;
import com.linkhub.oms.common.util.QtBeanUtil;
import com.linkhub.oms.dao.mpservice.ISupplierService;
import com.linkhub.oms.entity.SupplierEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @Description: SupplierBizService
 * @Author: echo
 * @Date: 2024/4/24 21:02
 * @Version: 1.0
 */
@Slf4j
@Service
public class SupplierBizServiceImpl implements SupplierBizService {

    @Resource
    private ISupplierService supplierService;


    @Override
    public List<SupplierVO> querySuppliers(String userId) {
        List<SupplierEntity> list = supplierService.listByUserId(userId);
        return QtBeanUtil.copyList(list, SupplierVO::new);
    }

    @Override
    public void save(SupplierAddParam param) {
        boolean existSupplier = supplierService.existSupplier(param.getUserId(), param.getSupplierName());
        if (existSupplier) {
            throw ExceptionFactory.getI18nBizException("supplier.exist.error");
        }

        SupplierEntity saveEntity = new SupplierEntity();
        QtBeanUtil.copyProperties(param, saveEntity);
        saveEntity.setUserId(param.getUserId());
        saveEntity.setSysSupplierId(IdUtil.getSnowflake().nextIdStr());
        saveEntity.setCreatedTime(LocalDateTime.now());
        saveEntity.setUpdateTime(LocalDateTime.now());
        supplierService.save(saveEntity);
    }

    @Override
    public void edit(String sysSupplierId, SupplierAddParam param) {
        // 查询  sysSupplierId userId
        SupplierEntity supplier = supplierService.getBySupplierId(param.getUserId(), sysSupplierId);
        if (Objects.isNull(supplier)) {
            throw ExceptionFactory.getI18nBizException("supplier.sysSupplierId.error");
        }
        // 判重
        boolean existSupplier = supplierService.existSupplier(param.getUserId(), param.getSupplierName(), sysSupplierId);
        if (existSupplier) {
            throw ExceptionFactory.getI18nBizException("supplier.exist.error");
        }

        SupplierEntity updateEntity = new SupplierEntity();
        QtBeanUtil.copyProperties(param, updateEntity);
        updateEntity.setId(supplier.getId());
        updateEntity.setUserId(null);
        supplierService.updateById(updateEntity);
    }
}
